<template>
  <div class="category" v-if="Object.keys(category.data).length > 0">
    <button @click="back" id="back"><span><</span><span>返回</span></button>
    <van-tabs v-model:active="active" @change="handleTabChange">
      <van-tab
        :title="item.name"
        v-for="item in selectedCategory.brotherCategory"
        :key="item.id"
      >
        <!-- 子组件-自定义 -->
        <current-category :currentCategory="selectedCategory.currentCategory" />
        <category-id-view :categoryId="categoryId.data" :key="active" />
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router'
import { useCategoryStore } from '../../../stores/category'
import { useCategoryIdStore } from '../../../stores/categoryId'
import { onMounted, ref } from 'vue'

//子组件
import currentCategory from './currentCategory.vue'
import categoryIdView from './categoryId.vue'

const route = useRoute()

const category = useCategoryStore()
const categoryId = useCategoryIdStore()

//当前选中的内容
const selectedCategory = ref(category.data) //导航栏
const selectedCategoryId = ref(category.data) //内容部分
const active = ref(0) //索引值

//获取数据
onMounted(async () => {
  await initData(route.query.id) //等待初始化数据
})

// 初始化
const initData = async (id) => {
  await category.fetchGetCategory(id)
  await categoryId.fetchGetCategoryId(id)
  // 强制触发响应式更新
  selectedCategory.value = { ...category.data }
  selectedCategoryId.value = { ...categoryId.data }
  active.value = category.data.brotherCategory.findIndex(
    (item) => item.id == id
  )
}

// 新增tab切换处理函数
const handleTabChange = (index) => {
  const item = selectedCategory.value.brotherCategory[index]
  if (item) {
    initData(item.id)
  }
}

//返回
const back = () => {
  history.back()
}
</script>

<style scoped>
.category {
  display: flex;
  flex-direction: column;
}
#back {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: 5px;
  padding: 10px;
  color: rgb(0, 38, 255);
  background-color: white;
  border: 0;
}
</style>
